<template>
  <div>
    <el-card class="box-card">
      <h2>删除用户</h2>
      <el-form :model="userForm" label-width="120px">
        <el-form-item label="选择用户：">
          <el-select v-model="selectedUser" placeholder="请选择用户">
            <el-option
                v-for="user in users"
                :key="user.username"
                :label="user.username"
                :value="user.username"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="deleteUser">删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userForm: {},
      users: [],
      selectedUser: null
    };
  },
  created() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      this.axios.get('/api/user/get')
          .then(response => {
            const result = response.data;
            if (Array.isArray(result.data)) {
              this.users = result.data;
            } else {
              console.error('Error: Expected an array but got:', result.data);
            }
          })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
    deleteUser() {
      const selectedUsername = this.selectedUser;
     console.log('Selected user:', selectedUsername); // 打印选择用户的名字
      this.axios.delete(`/api/user/delete/${selectedUsername}`)
          .then(() => {
            this.$message({
              message: '用户删除成功',
              type: 'success'
            });
            this.fetchUsers();
          })
          .catch(error => {
            console.error('Error deleting user:', error);
            this.$message.error('用户删除失败');
          });
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: auto;
  width: 600px;
}
</style>
